package com.code.generator.builder;

import java.io.IOException;
import java.util.Map;


import com.code.generator.ExceputionUtils;
import com.code.generator.GeneratorUtils;
import com.code.generator.entity.TableEntity;
import com.code.view.entity.HandlerVO;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;


/**
 * 创建myBatis的SqlMapper
 *
 *
 * @author 朱国军
 * @version 2014年8月30日 朱国军
 */
public class SqlMapperBuilder extends BaseBuilder {

    @Override
    public boolean builder(TableEntity tableEntity, String packagePath, HandlerVO handlerVO, Configuration cfg) {
        Map<String, Object> tableData = getDataMap(tableEntity, packagePath, handlerVO);
        try {
            /* 获取或创建一个模版 */
            Template temp = null;
            if (handlerVO.getMyBatis().getSelection()) {
                temp = cfg.getTemplate("sqlMapper_mybatis.ftl", "UTF-8");
            } else {
                temp = cfg.getTemplate("sqlMapper_ibatis.ftl", "UTF-8");
            }
            String filePath = handlerVO.getOutPutPath() +GeneratorUtils.getFilePath(packagePath)+ "/mapper/" + tableEntity.getClassName() + "Mapper.xml";
            GeneratorUtils.witeFile(filePath, temp, tableData);
        } catch (IOException e) {
            ExceputionUtils.logging("生成sqlMapper时数据库异常", e);
            return false;
        } catch (TemplateException e) {
            ExceputionUtils.logging("生成sqlMapper时模版异常", e);
            return false;
        } catch (Exception e) {
            ExceputionUtils.logging("生成sqlMapper时其他异常", e);
            return false;
        }
        return true;
    }
}
